package com.catazzz.springbootstudy.common;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.catazzz.springbootstudy.entity.SysUser;
import com.catazzz.springbootstudy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

/**
 * @作者: Tao
 * @日期: 2025/1/7
 * @时间: 22:01
 * @描述: <br><pre>
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 根据用户名加载用户详情<br>
     * 此方法用于Spring Security框架，以支持用户身份验证和授权<br>
     * 它通过查询数据库中的用户信息，并将其转换为Spring Security所需的UserDetails对象格式<br>
     *
     * @param username 用户名，用于查询用户信息
     * @return UserDetails对象，包含用户的基本信息和权限信息
     * @throws UsernameNotFoundException 如果指定用户名的用户不存在，则抛出此异常
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername, username));
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        return User.builder()
                // 设置用户名为系统用户的用户名
                .username(sysUser.getUsername())
                // 设置密码为系统用户的密码
                .password(sysUser.getPassword())
                // 将系统用户的角色字符串转换为Authority对象列表并设置
                .authorities(AuthorityUtils.commaSeparatedStringToAuthorityList(sysUser.getRole()))
                // 完成User实例的构建
                .build();
    }
}
